package net.xdclass.rbac_shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 必须设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 需要登录的接口，如果访问某个接口，需要登录没有登录，则调用此接口（如果不是前后分离，则跳转页面）
        shiroFilterFactoryBean.setLoginUrl("/pub/need_login");

        // 登录成功则跳转页面，前后端分离不需要跳转
        shiroFilterFactoryBean.setSuccessUrl("/");

        // 没有权限，未授权就会调用此接口。先验证登录--->在验证是否有权限
        shiroFilterFactoryBean.setUnauthorizedUrl("/pub/not_permit");

        // 拦截器路径，坑一，部分路径无法进行拦截，原因：使用的是hashmap，是无序的，应该改为LinkedHashMap
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 退出拦截器
        filterChainDefinitionMap.put("/logout","logout");
        // 无需登录可以访问的路径
        filterChainDefinitionMap.put("/pub/**","anon");
        // 需要认证才可以访问的权限
        filterChainDefinitionMap.put("/authc/**","authc");
        // 管理员角色才可以访问的权限
        filterChainDefinitionMap.put("/admin/**","roles[admin]");
        // 有编辑权限才可以访问
        filterChainDefinitionMap.put("/video/update","perms[video_update]");
        // 坑二：过滤器链是顺序执行的，从上而下，一般/** 要放到最下面

        //authc: url必须通过认证才可以访问
        //anon: url可以匿名访问
        filterChainDefinitionMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(customRealm());
        manager.setSessionManager(sessionManager());

        return manager;
    }

    @Bean
    public CustomRealm customRealm(){
        CustomRealm customRealm = new CustomRealm();
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("md5");
        // hash次数
        matcher.setHashIterations(2);
        return matcher;
    }

    @Bean
    public SessionManager sessionManager(){
        CustomSessionManager sessionManager = new CustomSessionManager();
        return sessionManager;
    }
}
